#include "Principal.hpp"

using namespace BFT::membership;


Principal::Principal() //dummy object
{} 

Principal::Principal(in_addr_t _addr, uint16_t _port, std::string _pubKeyString)
{
	address = _addr;
	uint_port = _port;
	pubKeyString = _pubKeyString;
}

Principal::Principal(in_addr_t _addr, uint16_t _port, std::string _pubKeyString, void* _macKey)
{
	address = _addr;
	uint_port = _port;
	pubKeyString = _pubKeyString;
}

Principal::Principal(std::string _string, std::string _pubKeyString)
{
	size_t pos=0;
	pos=_string.find(':');

        if ( inet_aton(_string.substr(0,pos).c_str(), (struct in_addr*)&address) == 0)
        {
        	
		struct addrinfo hints;
		struct addrinfo *result;
		int s;

        	memset(&hints, 0, sizeof(struct addrinfo));
		hints.ai_family = AF_UNSPEC;    /* Allow IPv4 or IPv6 */
		hints.ai_socktype = 0; 
		hints.ai_flags = AI_PASSIVE;    /* For wildcard IP address */
		hints.ai_protocol = 0;          /* Any protocol */
		hints.ai_canonname = NULL;
		hints.ai_addr = NULL;
		hints.ai_next = NULL;

		s = getaddrinfo(_string.substr(0,pos).c_str(), NULL , &hints, &result);
		if (s != 0) {
			fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(s));
			exit(EXIT_FAILURE);
		}

		/* getaddrinfo() returns a list of address structures.
		   we take the address of the first structure
		*/
		 address = ((sockaddr_in*)result->ai_addr)->sin_addr.s_addr;
		 freeaddrinfo(result);
        	
        }
        uint_port = atoi( _string.substr(pos+1).c_str());
	
	pubKeyString = _pubKeyString;
	//TODO: create public key NOW!
	//fprintf(stderr,"Principal constructor: should also create the real public key now... \n");	
}

void Principal::getPublicKey()
{
	fprintf(stderr,"Principal::getPublicKey NIY\n");
	exit(18);
}

void Principal::getMacKey()
{
	fprintf(stderr,"Principal::getMacKey NIY\n");
	exit(19);
}

void Principal::setMacKey()
{
	fprintf(stderr,"Principal::setMacKey NIY\n");
	exit(20);
}

void Principal::printInfo()
{
	fprintf(stdout,"Principal information:\n");
	fprintf(stdout,"IP address.....:%s\n",inet_ntoa(*(struct in_addr*)&address));
	fprintf(stdout,"Port number....:%d\n",uint_port);
	fprintf(stdout,"PubKeyString...:%s\n",pubKeyString.c_str());
}
